package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.article.domain.ZPraiseLog;
import com.ruoyi.article.domain.vo.AppUserInfo;
import com.ruoyi.article.service.IZPraiseLogService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IZPraiseLogService zPraiseLogService;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    public AjaxResult getUserInfo(String token) {

        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = tokenService.parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = tokenService.getTokenKey(uuid);
                LoginUser user = redisCache.getCacheObject(userKey);
                if (StringUtils.isNotNull(user)) {
                    //数据处理
                    AppUserInfo appUserInfo = handleUser(user);
                    return AjaxResult.success(appUserInfo);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        return AjaxResult.error(401, "token无效");
    }

    private AppUserInfo handleUser(LoginUser user) {
        AppUserInfo appUserInfo = new AppUserInfo();
        appUserInfo.setUserId(user.getUserId());
        appUserInfo.setUserName(user.getUsername());
        appUserInfo.setNickName(user.getUser().getNickName());
        appUserInfo.setAvatar(user.getUser().getAvatar());
        appUserInfo.setSex(user.getUser().getSex());
        appUserInfo.setEmail(user.getUser().getEmail());
        appUserInfo.setPhone(user.getUser().getPhonenumber());
        appUserInfo.setCreateTime(user.getUser().getCreateTime());
        appUserInfo.setLoginDate(user.getUser().getLoginDate());
        appUserInfo.setLoginIp(user.getUser().getLoginIp());
        QueryWrapper<ZPraiseLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getUserId())
                .groupBy("status")
                .select("status", "COUNT(*) as count");

        // 执行查询，获取分组后的聚合结果
        List<Map<String, Object>> maps = zPraiseLogService.listMaps(wrapper);


        for (Map<String, Object> map : maps) {
            String status = (String) map.get("status");
            Long count = (Long) map.get("count");
            //0:文章点赞，1:文章收藏，评论点赞:2
            switch (status) {
                case "0":
                    appUserInfo.setPraise(String.valueOf(count));
                    break;
                case "1":
                    appUserInfo.setCollect(String.valueOf(count));
                    break;
                case "2":
                    appUserInfo.setComment(String.valueOf(count));
                    break;
                default:
            }

        }
        return appUserInfo;
    }
}
